from invidious import Channel as channel

from src.vobjects.video import Video
from src.vobjects.item import Item

from src.config import Config
from src.constants import *
from src.utils import *

class Channel(channel):

    def to_item(self):
        subs = f"{convert_big_nums(self.subCount)} subs"

        subtitle = ""
        is_subscribed, _, _ = self.is_subscribed()
        if is_subscribed: subtitle = SUBSCRIBED_CHANNEL_SUBTITLE

        status = {
            "url" : self.authorUrl
        }

        return Item(self.title, f"{self.videoCount} vids", subs, "", self, subtitle=subtitle, status=status)

    def from_json(self, jsn):
        self.title          = jsn['title']
        self.authorId       = jsn['authorId']
        self.latestVideos   = jsn['videos']

        videos = list()
        for videojs in self.latestVideos:
            video = Video()
            video.from_json(videojs)
            videos.append(video)
        self.videos = videos
        self.videoCount = len(self.videos)

        return self

    def is_subscribed(self, url: str=""):
        cfg = Config()
        subs_path = cfg.subs_path

        url = self.authorUrl[9:]
        subLine = -1

        with open(subs_path, 'r') as file:
            lines = file.readlines()
            for line in lines:
                subLine += 1
                if url in line: return True, subLine, lines

        return False, subLine, None

    def subscribe(self): 
        cfg = Config()
        subs_path = cfg.subs_path

        is_subscribed, _, _ = self.is_subscribed()
        if is_subscribed: return

        url = self.authorUrl[9:]

        with open(subs_path, 'r') as file:
            for line in file.readlines():
                if url in line: return file.close()
            file.close()

        with open(subs_path, 'a') as file:
            file.write(url+'\n')
            file.close()
    
    def unsubscribe(self):
        cfg = Config()
        subs_path = cfg.subs_path

        is_subscribed, _, _ = self.is_subscribed()
        if not is_subscribed: return

        url = self.authorUrl[9:]
        lines = []

        with open(subs_path, 'r') as file:
            lines = file.readlines()

        with open(subs_path, 'w') as file:
            for line in lines:
                if url not in line:
                    file.write(line)


